<?php

namespace RegisterUser\Controller;

require_once ('RegisterUser/Model/RegisterUserModel.php');

class RegisterUserController {

	private $registerUserModel;
	private $registerUserView;

	function __construct($RegisterUserView) {
		$this -> registerUserModel = new \RegisterUser\Model\RegisterUserModel();
		$this -> registerUserView = $RegisterUserView;
	}

	public function wantsToRegister() {
		if (isset($_POST['registerNewUser'])) {
			$_SESSION['doingRegistration'] = '';
			return TRUE;
		} else {
			return FALSE;
		}
	}

	public function doingRegistration() {
		$newUsername = $_POST['newUsername'];
		if (isset($_POST['Back'])) {
			unset($_SESSION['doingRegistration']);
			return FALSE;
		} elseif (isset($_SESSION['doingRegistration'])) {
			if ($this -> didRegistration()) {
				return FALSE;
			} else {
				$this -> registerUserView -> setUsername($newUsername);
				return TRUE;
			}
		} else {
			return FALSE;
		}
	}

	/**
	 * @return Returns TRUE if the user completed his registration
	 */
	public function didRegistration() {
		$newUsername = $_POST['newUsername'];
		$newPassword = $_POST['newPassword'];
		$newPasswordRepeated = $_POST['newPasswordRepeated'];
		if (isset($_POST['Register'])) {
			if ($this -> registerUserModel -> tryToRegister($newUsername, $newPassword, $newPasswordRepeated)) {
				$this -> sendMessage();				
				return TRUE;
			} else {
				$this -> sendMessage();
				return FALSE;
			}
		} else {
			return FALSE;
		}
	}

	private function sendMessage() {
		foreach ($this->registerUserModel->messageArray as $message) {
			$this -> registerUserView -> setErrorMessage($message);
		}
	}

}
